/**
 * @Title: SessionUtil.java
 * @Package com.webgis.common.utils
 */
package me.springboot.mybatis.common.utils;

import com.alibaba.fastjson.JSON;
import me.springboot.mybatis.core.RetCode;
import me.springboot.mybatis.exception.ResultException;
import me.springboot.mybatis.model.User;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;

/**
 * *********************************
 *
 * @ClassName: SessionUtil.java
 * @Description: session管理
 * @author: zengh
 * @createdAt: 2015年6月3日下午2:45:21
 * *********************************
 */
public class SessionUtil {
    private static final Logger logger = Logger.getLogger(SessionUtil.class);

    /**
     * @param request
     * @param sessionKey
     * @param obj
     * @Title: setAttribute
     * @Description: 添加对象到session的统一入口
     * @createdBy:luomingguo
     * @createaAt:2015年6月3日下午2:45:34
     */
    public static void setAttribute(HttpServletRequest request, String sessionKey, Object obj) {
        request.getSession().setAttribute(sessionKey, obj);
    }


    /**
     * @param request
     * @param sessionKey
     * @return
     * @Title: getAttribute
     * @Description: 从session中获取对象的统一入口
     * @createdBy:luomingguo
     * @createaAt:2015年6月3日下午2:45:43
     */
    public static Object getAttribute(HttpServletRequest request, String sessionKey) {
        return request.getSession().getAttribute(sessionKey);
    }

    /**
     * @param request
     * @param sessionKey
     * @return
     * @Title: getAttributeStr
     * @Description: 以string格式返回session
     * @createdBy:Luomingguo
     * @createaAt:2015年10月10日上午11:29:38
     */
    public static String getAttributeStr(HttpServletRequest request, String sessionKey) {
        Object o = getAttribute(request, sessionKey);
        if (o != null) {
            return o.toString();
        }
        return null;
    }

    /**
     * @param request
     * @param sessionKey
     * @return
     * @Title: getAttributeInt
     * @Description: 以Integer格式返回session
     * @createdBy:Luomingguo
     * @createaAt:2015年10月10日上午11:33:55
     */
    public static Integer getAttributeInt(HttpServletRequest request, String sessionKey) {
        Object o = getAttribute(request, sessionKey);
        if (o != null && StringUtil.isNumeric(o.toString(), true)) {
            return Integer.parseInt(o.toString());
        }
        return null;
    }


    /**
     * @param request
     * @param sessionKey
     * @Title: removeAttribute
     * @Description: 删除session key
     * @createdBy:luomingguo
     * @createaAt:2015年6月3日下午2:45:52
     */
    public static void removeAttribute(HttpServletRequest request, String sessionKey) {
        request.getSession().removeAttribute(sessionKey);
    }

    public static void removeUser(HttpServletRequest request) {
        String token = getToken(request);
        request.getSession().removeAttribute(token);
    }

    public static String setSessionUser(HttpServletRequest request, User user) {
        String token = UUIDGenerator.getUUID() + "_" + user.getuId();
        request.getSession().setAttribute(token, user);
        logger.info("++++++++++++++++setSessionUser:" + JSON.toJSONString(request.getSession().getAttributeNames()));
        return token;
    }

    /**
     * @param request
     * @return
     * @Title: getSessionUser
     * @Description: 返回session中的User
     * @createdBy:luomingguo
     * @createaAt:2015年6月3日下午2:46:01
     */
    public static User getSessionUser(HttpServletRequest request, String sessionKey) {
        Object o = request.getSession().getAttribute(sessionKey);
        if (o != null) {
            return (User) o;
        } else {
            return null;
        }
    }

    public static User getSessionUser(HttpServletRequest request) throws ResultException {
        String token = getToken(request);
        if (StringUtil.isBlank(token)) {
            throw new ResultException(RetCode.NOT_LOGIN.getCode(), "登录失效");
        }
        logger.info("=========================");
        logger.info(JSON.toJSON(request.getSession().getAttributeNames()));
        Object o = request.getSession().getAttribute(token);
        if (o != null) {
            return (User) o;
        } else {
            throw new ResultException(RetCode.NOT_LOGIN.getCode(), "登录失效");
        }
    }

    public static String getToken(final HttpServletRequest req) {
        String token = req.getParameter("token");
        /*Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    try {
                        return URLDecoder.decode(cookie.getValue(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        logger.error("转码错误");
                    }
                }
            }
        }*/
        return token;
    }
}
